package com.northwind.realm;

import com.northwind.dao.AdminDao;
import com.northwind.entity.Admin;
import com.northwind.entity.Authority;
import com.northwind.entity.Role;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class MyRealm extends AuthorizingRealm {
    @Resource
    AdminDao adminDao;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //强转
        UsernamePasswordToken tokens = (UsernamePasswordToken)authenticationToken;
        //获取token中的身份信息
        String username = tokens.getUsername();
        Admin admin = adminDao.queryByUsername(username);
        AuthenticationInfo info = null;
        if(admin != null){
            //创建info对象   数据库取出的信息  身份信息   凭证信息   随机盐  realm名
            info = new SimpleAuthenticationInfo(
                    admin.getUsername(),admin.getPassword(), ByteSource.Util.bytes(admin.getSalt()),this.getName()
            );
        }
        return info;
    }


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户的主身份

        String username = (String) principalCollection.getPrimaryPrincipal();
        Admin admin = adminDao.queryByUsernameShiro(username);
        //创建角色标识(角色名)集合
        ArrayList<String> roleList = new ArrayList<>();
        //创建标识(权限名)集合
        ArrayList<String> permissionList = new ArrayList<>();
        //获取角色集合
        List<Role> roleLists = admin.getRoleList();
        //遍历角色集合
        for(Role role : roleLists){
            //将角色名放入新的角色集合
            roleList.add(role.getRoleName());
            //获取权限集合
            List<Authority> authorityList = role.getAuthorityList();
            //遍历权限集合
            for (Authority authority : authorityList) {
                permissionList.add(authority.getAuthorityName());
            }
        }
        SimpleAuthorizationInfo info = null;
        if(admin != null){
            info = new SimpleAuthorizationInfo();
            //给当前主体授予多个角色
            info.addRoles(roleList);
            //给当前主体对象赋予多个权限
            info.addStringPermissions(permissionList);
        }
        return info;
    }


}
